// pages/question/question.js
import urlconf from '../../utils/urlconf.js'
import httpRequest from '../../utils/request.js'
// const WxParse = require('../../wxParse/wxParse.js'); // 富文本解析
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 值为0禁止切换动画
        swiperDuration: "250",
        list: [],
        examArr: [], //整张试卷信息
        tabSelectedIndex: 0, //页数 滑动到的位置
        examInfo: '', //当前页题信息
        examId: '', //试卷id
        optionsArr: ['A', 'B', 'C', 'D', 'E'],
        examName: ''
    },
    changeIndexEvent(v) {
        let examArr = this.data.examArr;
        let index = v.detail.current;
        let tabSelectedId = examArr[index].id;
        this.querytTabSelectedSearch(tabSelectedId, examArr);
    },
    onClickAnswerCard: function (e) {
        let userInfo = wx.getStorageSync('userInfo')
        if (!userInfo) { //未登录
            wx.navigateTo({
                url: `../login/login`
            })
            return;
        }
        let that = this;
        // 跳转前将动画去除，以免点击某选项回来后切换的体验很奇怪
        that.setData({
            swiperDuration: "0"
        })
        wx.navigateTo({
            url: `../question_answer_card/question_answer_card?examId=${this.data.examId}&&countNum=${this.data.countNum}&&name=${this.data.examName}`
        })
    },

    onClickLast: function (e) {
        let that = this
        let lastIndex = that.data.tabSelectedIndex == 0 ? that.data.examArr.length - 1 : that.data.tabSelectedIndex - 1
        if (lastIndex == that.data.examArr.length - 1) {
            wx.showToast({
                title: '已经是第一题',
                icon: 'none'
            })
            return;
        }
        that.setData({
            tabSelectedIndex: lastIndex
        })
    },

    onClickNext: function (e) {
        let that = this
        let nextIndex = that.data.tabSelectedIndex == that.data.examArr.length - 1 ? 0 : that.data.tabSelectedIndex + 1
        if (nextIndex == 0) {
            wx.showToast({
                title: '已经是最后一题',
                icon: 'none'
            })
            return;
        }
        that.setData({
            tabSelectedIndex: nextIndex
        })
    },
    queryCourseList(id) {
        return new Promise((resolve, reject) => {
            let param = {
                examId: this.data.examId,
                num: id + 1
            }
            console.log(param);
            httpRequest(urlconf.getQues, param, 'get').then(res => {
                console.log('获取试题result', res);
                if (res.code == 1) {
                    let optionsUser = []
                    let options = res.data.options ? res.data.options.split("|") : []
                    let answer = res.data.answer ? res.data.answer.split(",") : []
                    let choose = res.data.chose ? res.data.chose.split(",") : []
                    res.data.type = answer.length > 1 ? 2 : 1
                    options.map((item, i) => {
                        let optionUserObj = {}
                        optionUserObj.option = this.data.optionsArr[i]
                        optionUserObj.topic = item
                        optionUserObj.iscorrect = answer.indexOf(i.toString()) != -1 ? true : false
                        optionUserObj.checked = choose.indexOf(i.toString()) != -1 ? true : false
                        optionsUser.push(optionUserObj)
                    })
                    res.data.optionsUser = optionsUser
                    res.data.clt = res.data.clt.replace(/\<img/gi, '<img style="max-width:100%;height:auto"')
                    res.data.txt = res.data.txt.replace(/\<img/gi, '<img style="max-width:100%;height:auto"')
                    res.data.parsing = this.removeWordXml(res.data.parsing)
                    resolve(res.data)
                } else {
                    wx.showToast({
                        title: '获取试题失败',
                        icon: ''
                    })
                }
            })
        })
    },
    querytTabSelectedSearch(tabSelectedId, examArr) {
        let _self = this
        let tabSelectedIndex;
        examArr.map((item, index) => {
            if (item.id == tabSelectedId) {
                tabSelectedIndex = index
            }
        })
        wx.showLoading({
            title: '加载中',
        })

        this.setData({
            tabSelectedIndex
        }, () => {
            this.queryCourseList(tabSelectedId)
                .then((examInfo) => {
                    examArr.map((item, index) => {
                        if (item.id == tabSelectedId) {
                            item['examInfo'] = examInfo
                        }
                    })
                    console.log(examArr);
                    let timer = setTimeout(() => {
                        this.setData({
                            examArr,
                            examInfo
                        }, () => {
                            // console.log(examInfo.clt);
                            // WxParse.wxParse('details', 'html', examInfo.clt, _self, 5);
                            wx.hideLoading()
                        })
                        clearTimeout(timer);
                    }, 300)

                })
                .catch((err) => {
                    console.error('tabSelected事件请求课程列表错误', err);
                    wx.hideLoading()

                })
        })
    },
    chooseSingle(e) {
        let userInfo = wx.getStorageSync('userInfo')
        if (!userInfo) { //未登录
            wx.navigateTo({
                url: `../login/login`
            })
            return
        }
        console.log(e);
        let {examInfo, examArr} = this.data
        let {examnum, optionindex, ischecked, type, isdone} = e.currentTarget.dataset
        console.log('是否已交卷', isdone);
        if (isdone) { //该试卷已经提交
            return;
        }
        if (ischecked && type == 1) {
            return
        }
        examInfo.optionsUser.map((item, i) => {
            if (type == 1) { //单选
                if (optionindex == i) { //判断当前选中选项
                    item.checked = true
                } else {
                    item.checked = false
                }
            } else { //多选
                if (optionindex == i) { //判断当前选中选项
                    item.checked = !item.checked
                }
            }

        })
        examArr.map((item, i) => {
            if (item.id == examnum) {
                item.examInfo = examInfo
            }
        })
        this.setData({
            examArr
        })
        let chooseAnswer = []
        examInfo.optionsUser.map((item, i) => {
            if (item.checked) {
                chooseAnswer.push(i)
            }
        })
        let param = {
            examId: Number(this.data.examId),
            num: examnum + 1,
            option: chooseAnswer.join(',')
        }
        console.log(param);
        wx.setStorageSync('historyIndex', examnum)
        httpRequest(urlconf.everyRecord, param, 'POST').then(res => {
            console.log('提交答案result', res);
            if (res.code == 1) {

            } else {
                wx.showToast({
                    title: res.msg,
                    icon: 'none',
                })
                let timer = setTimeout(() => {
                    wx.navigateBack({
                        delta: 1
                    });
                    clearTimeout(timer);
                }, 1000)

            }
        })

    },
    isCorrect(choose, correctArr) {
        console.log(choose, correctArr);
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options);
        wx.setNavigationBarTitle({
            title: options.name ? options.name : '估分助手'
        })
        let that = this
        that.setData({
            swiperHeight: wx.getSystemInfoSync().windowHeight,
            examId: options.examId,
            countNum: options.nums,
            examName: options.name
        })

        // let countNum = this.data.countNum;
        // let examArr = []
        // for (let i = 0; i < countNum; i++) {
        //     examArr.push({
        //         id: i
        //     })
        // }
        // let lastDoQuestionIndex = 9 // 历史记录
        // examArr.map((item, index) => {
        //     if (lastDoQuestionIndex == item.id) {
        //         this.querytTabSelectedSearch(item.id, examArr)
        //     }
        // })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let countNum = this.data.countNum;
        let examArr = []
        for (let i = 0; i < countNum; i++) {
            examArr.push({
                id: i
            })
        }
        let lastDoQuestionIndex = wx.getStorageSync('historyIndex')
        if (!lastDoQuestionIndex) {
            lastDoQuestionIndex = 0
        }
        console.log('页数', lastDoQuestionIndex + 1);
        examArr.map((item, index) => {
            if (lastDoQuestionIndex == item.id) {
                this.querytTabSelectedSearch(item.id, examArr)
            }
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        let shareImgUrl = app.globalData.shareImg
        return {
            imageUrl: shareImgUrl,
            path: '/pages/index/index'
        };
    },
    removeWordXml(text) {
        var html = text;
        html = html.replace(/<\/?SPANYES[^>]*>/gi, "");//  Remove  all  SPAN  tags
        html = html.replace(/<\/?spantimes[^>]*>/gi, "");//  Remove  all  SPAN  tags
        // html = html.replace(/<(\w[^>]*)  class=([^|>]*)([^>]*)/gi, "<$1$3");  //  Remove  Class  attributes
        // html = html.replace(/<(\w[^>]*)  style="([^"]*)"([^>]*)/gi, "<$1$3");  //  Remove  Style  attributes
        html = html.replace(/<(\w[^>]*)  lang=([^|>]*)([^>]*)/gi, "<$1$3");//  Remove  Lang  attributes
        html = html.replace(/<\\?\?xml[^>]*>/gi, "");//  Remove  XML  elements  and  declarations
        html = html.replace(/<\/?\w+:[^>]*>/gi, "");//  Remove  Tags  with  XML  namespace  declarations:  <o:p></o:p>
        html = html.replace(/&nbsp;/, "");//  Replace  the  &nbsp;
        html = html.replace(/\n(\n)*( )*(\n)*\n/gi, '\n');
        html = html.replace("<!--\[if gte mso 9]><xml>\n</xml><!\[endif]-->", "")
        //  Transform  <P>  to  <DIV>
        // var  re  =  new  RegExp("(<P)([^>]*>.*?)(<//P>)","gi")  ;            //  Different  because  of  a  IE  5.0  error
        // html = html.replace(re, "<div$2</div>");
        return html;
    }
})
